package net.zhengxinyun.performance.service.login;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.MD5;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryUnitIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.TownIndicatorsEntityMapper;
import net.zhengxinyun.performance.mapper.login.RolePerMapper;
import net.zhengxinyun.performance.mapper.login.UserEntityMapper;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther: hyp
 * @Date: 2018/10/30 14:39
 */
@Service
public class UserServiceImpl implements UserService {

    private UserEntityMapper userEntityMapper;


    @Autowired
    private DepartmentEntityMapper departmaper;

    @Autowired
    private LoginService loginService;

    @Autowired
    private RolePerMapper rolePerMapper;

    @Autowired
    private TownIndicatorsEntityMapper townIndicatorsEntityMapper;
    @Autowired
    private CountryIndicatorsEntityMapper cityIndexMapper;
    @Autowired
    private CountryUnitIndicatorsEntityMapper departIndexMapper;

    @Autowired
    public UserServiceImpl(UserEntityMapper userEntityMapper) {
        this.userEntityMapper = userEntityMapper;
    }

    @Override
    public int delete(UserEntity userEntity) {
        return userEntityMapper.deleteByPrimaryKey(userEntity.getId());
    }

    @Override
    public int update(UserEntity userEntity) throws Exception {
        if (StringUtils.isNotBlank(userEntity.getUserPassword())) {
            UserEntity entity = userEntityMapper.selectByPrimaryKey(userEntity.getId());
            if (!entity.equals(userEntity.getUserPassword())) {
                String passWord = MD5.md5(userEntity.getUserPassword(), MD5.MD5_STR);
                userEntity.setUserPassword(passWord);
            }
        }
        return userEntityMapper.updateByPrimaryKey(userEntity);
    }

    @Override
    public int insert(UserEntity userEntity) {
        return userEntityMapper.insert(userEntity);
    }

    @Override
    public List<UserFilter> query(UserFilter userFilter) {
        return userEntityMapper.query(userFilter);
    }

    @Override
    public UserEntity queryById(Long id) {
        return userEntityMapper.selectByPrimaryKey(id);
    }

    @Override
    public Integer queryForCount(UserFilter userFilter) {
        return userEntityMapper.queryForCount(userFilter);
    }

    @Override
    public List<String> queryForDepartment() {
        return userEntityMapper.queryForDepartment();
    }

    @Override
    public List<UserFilter> queryUsers(UserFilter userFilter) {
        return userEntityMapper.queryAllUsers(userFilter);
    }

    @Override
    public int saveloginLog(LoginLog log) {
        return userEntityMapper.saveLoginLog(log);
    }

    @Override
    public List<LoginLog> findByUserId(UserFilter userid) {
        return userEntityMapper.findByUserId(userid);
    }

    @Override
    public int updateByPrimaryKeySelective(UserEntity entity) {
        return userEntityMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public int queryForCountLog(UserFilter userFilter) {
        return userEntityMapper.queryForCountLog(userFilter);
    }

    @Override
    public String getCurrentYear() {
        return userEntityMapper.selectCurrentYear();
    }

    /**
     * 20190709
     * @param id
     * @return
     */
    @Override
    public UserEntity getUseInfo(Long id) {
        return userEntityMapper.getUserInfoById(id);
    }


    /**
     * 保存新用户
     */
    @Override
    public String saveUserInfo(UserEntity userEntity, TokenEntity tokenEntity, HttpServletRequest request) {
        UserEntity Userinfo = loginService.getUserByToken(tokenEntity);
        String passWord = null;
        try {
            passWord = MD5.md5(userEntity.getUserPassword(), MD5.MD5_STR);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置密码
        userEntity.setUserPassword(passWord);
        //插入前先检测 是否已经有用户
        UserFilter userFilter = new UserFilter();
        userFilter.setUserName(userEntity.getUserName());
        List<UserFilter> userlists = this.query(userFilter);
        if (userlists.size() > 0) {
            return "添加失败，该用户已经存在，请重试";
        }

        /**
         * 角色不为空，取角色值，其他自定义权限为空
         */
        if (ObjectUtils.isNotBlank(userEntity.getRoleid())) {
            userEntity.setIndexRight(null);//县对乡镇权限
            userEntity.setBtnRight(null);//按钮权限
            userEntity.setRoleRight(null); //菜单
            userEntity.setDepartIndex(null);
            userEntity.setCityIndex(null);
            //userEntity.setHaveRight(null);//拥有的菜单
        }else {
            //角色值为空， 取按照自定义权限来。

            /**
             * 菜单权限
             */
            if (ObjectUtils.isNotBlank(userEntity.getCheckAllGroup())) {
                List<String> rights = userEntity.getCheckAllGroup();
                String roleRight = String.join(",", rights);
                userEntity.setRoleRight(roleRight);
                /**
                 * 拥有可操作的的菜单总量
                 */
                userEntity.setHaveRight(roleRight);
            }
            /**
             * 按钮权限
             */
            if (ObjectUtils.isNotBlank(userEntity.getBtnRights())) {
                List<String> btnRights =userEntity.getBtnRights();
                String StrBtnRight = String.join(",", btnRights);
                userEntity.setBtnRight(StrBtnRight);
            }
            /**
             * 指标权限 县对乡镇
             */
            if (ObjectUtils.isNotBlank(userEntity.getCheckAllindexGroup())) {
                List<String> indexList = userEntity.getCheckAllindexGroup();
                String strIndex = String.join(",", indexList);
                userEntity.setIndexRight(strIndex);
                // param.rolePerEntity.setHaveIndexs(strIndex);
            }
             /*
                    市指标
             */
            if(ObjectUtils.isNotBlank(userEntity.getCheckCityGroup()))
            {
                List<String> indexList = userEntity.getCheckCityGroup();
                String strIndex  = String.join(",",indexList);
                userEntity.setCityIndex(strIndex);
            }

            /*
             *      单位指标
             */
            if(ObjectUtils.isNotBlank(userEntity.getCheckUnitGroup()))
            {
                List<String> indexList = userEntity.getCheckUnitGroup();
                String strIndex  = String.join(",",indexList);
                userEntity.setDepartIndex(strIndex);
            }

            userEntity=  checkIndexRight(userEntity,request);

        }

        if("admin".equals(Userinfo.getUserPermissions()))
        {
            userEntity.setCreater(Userinfo.getUserPermissions());
        }else {
            userEntity.setCreater(Userinfo.getId().toString());
        }

        userEntity.setId(null);
        int i = this.insert(userEntity);
        if(i==0)
        {
            return  "保存失败";
        }
        return "保存成功";
    }

    /*
        校验三大指标（市指标，县指标，单位指标）权限
     */
    public UserEntity checkIndexRight(UserEntity userEntity,HttpServletRequest request)
    {
        //先确实是否为乡镇用户 乡镇用户所有 县对乡镇的指标都可以看，默认全部勾上。 市指标和单位指标没权限。
        String year = (String) request.getSession().getAttribute("currentYear");
        DepartmentEntity departmentEntity = departmaper.selectByCode(userEntity.getDepartcode());
        TownIndicatorsFilter townfilter = new TownIndicatorsFilter();
        townfilter.setPageSize(0);
        townfilter.setIndexType("二级指标");
        townfilter.setDateTime(year);

       if("乡镇".equals(departmentEntity.getDepartType()))
       {
           //县指标 默认全勾选上

        if(StringUtils.isBlank(userEntity.getIndexRight()))
        {

            List<TownIndicatorsFilter> listIndex = townIndicatorsEntityMapper.query(townfilter);
            String indexRight ="";
            for (TownIndicatorsFilter item: listIndex)
            {
                indexRight=item.getId()+","+indexRight;
            }
            userEntity.setIndexRight(indexRight);

        }

       }else
       {
           //townIndex
            if(StringUtils.isBlank(userEntity.getIndexRight()))
            {
                townfilter.setLeadUnit(departmentEntity.getDepartcode());
                List<TownIndicatorsFilter> listIndex = townIndicatorsEntityMapper.query(townfilter);
                String indexRight ="";
                for (TownIndicatorsFilter item: listIndex)
                {
                    indexRight=item.getId()+","+indexRight;
                }
                userEntity.setIndexRight(indexRight);
            }


            //cityIndex
           if(StringUtils.isBlank(userEntity.getCityIndex()))
           {
               CountryIndicatorsFilter cityfiler = new CountryIndicatorsFilter();
               cityfiler.setPageSize(0);
               cityfiler.setLeadUnit(userEntity.getDepartcode());
               cityfiler.setDateTime(year);
               List<CountryIndicatorsFilter> cityIndexs = cityIndexMapper.query(cityfiler);
               String cityIndex ="";
               for (CountryIndicatorsFilter item: cityIndexs )
               {
                   cityIndex = item.getId()+","+cityIndex;
               }
               userEntity.setCityIndex(cityIndex);
           }


           // departIndex
           if(StringUtils.isBlank(userEntity.getDepartIndex()))
           {
               CountryUnitIndicatorsFilter departFilter = new CountryUnitIndicatorsFilter();
               departFilter.setLeadUnit(userEntity.getDepartcode());
               departFilter.setDateTime(year);
               departFilter.setPageSize(0);
               List<CountryUnitIndicatorsEntity> departIndexs = departIndexMapper.query(departFilter);
               String departIndex="";
               for (CountryUnitIndicatorsEntity item:departIndexs )
               {
                   departIndex= item.getId()+","+departIndex;
               }
               userEntity.setDepartIndex(departIndex);
           }



       }



        return userEntity;
    }


    /*
        文本导入批量校验
     */
    @Override
    public HashMap<String,List<String>> batchUpdateUser(List<UserFilter> userlist,String checkCode) {

        List<String> errorInfo = new ArrayList<>();
        List<String> warinlist = new ArrayList<>();

        for( UserFilter user: userlist)
        {
            int flg = 0;
            Long id = user.getId();
            UserEntity userEntity = userEntityMapper.selectByPrimaryKey(id);
            if(ObjectUtils.isBlank(userEntity))
            {
                userEntity  = new UserEntity();
                flg =1;

                UserFilter userFilter = new UserFilter();
                userFilter.setUserName(user.getUserName());
                List<UserFilter> list = userEntityMapper.query(userFilter);
                if(ObjectUtils.isNotBlank(list)){
                    errorInfo.add("错误信息：用户名:"+user.getUserName()+"已存在，无法进行增员操作");
                    continue;
                }else {
                    warinlist.add("警告信息：用户名为： "+user.getUserName()+"不存在，系统将会进行新增操作。");
                }


            }
            /*
                匹配密码
             */
            userEntity.setUserPassword(matchPwd(user.getUserPassword(),userEntity.getUserPassword()));

            /*
                匹配单位
             */
            String departcode = matchDepart(user.getDepartment());
            if("error".equals(departcode))
            {
                System.out.println("找不到-----------"+user.getDepartment()+"----------");
                errorInfo.add("用户ID："+id+"用户名："+user.getUserName()+" 无法匹配单位");
                continue;

            }else {
                userEntity.setDepartcode(departcode);
            }
            /*
                匹配角色
             */
            String roleId  = matchRole(user.getRoleid(),userEntity.getRoleid(),user.getRoleName());
            if(StringUtils.isNotBlank(roleId))
            {
                if("error".equals(roleId)){
                    errorInfo.add("错误信息:角色名无法匹配角色,错误信息不会被更新或者保存。用户ID："+id+",用户名："+user.getUserName()+"");
                    continue;
                }

                Long roid = Long.parseLong(roleId);
                userEntity.setRoleid(roid);
            }else {
                warinlist.add("警告信息:角色值为空，可上传后自行更新。用户ID："+id+",用户名："+user.getUserName()+"，");
                userEntity.setRoleid(null);
            }


            /*
                  执行操作
             */
            if("1".equals(checkCode)  ){
                userEntity.setNickName(user.getNickName());
                userEntity.setIsManger(user.getIsManger());
                userEntity.setUserPosition(user.getUserPosition());
                userEntity.setUserPhone(user.getUserPhone());
                if(flg==1){
                    userEntity.setUserName(user.getUserName());
                    userEntity.setId(null);
                    this.insert(userEntity);
                }else {
                    try {
                        this.update(userEntity);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }



            }


        }
        HashMap<String,List<String>> map = new HashMap<>();
        map.put("error",errorInfo);
        map.put("warn",warinlist);
        return map;
    }

    /**
     * 匹配密码
     * @param Newpwd
     * @param oldPwd
     * @return
     */
    public String  matchPwd(String Newpwd ,String oldPwd )
    {
        if(!Newpwd.equals(oldPwd)){
            try {
                String pwd = MD5.md5(Newpwd,MD5.MD5_STR);
                return  pwd;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return oldPwd;
    }

    /**
     * 匹配单位
     * @param departName
     * @return
     */
    public String  matchDepart(String departName){

        DepartmentEntity departmentEntity = null;

        if(StringUtils.isNotBlank(departName))
        {
            departmentEntity= departmaper.getDepartByName(departName);
        }


          if(ObjectUtils.isNotBlank(departmentEntity)){
              return  departmentEntity.getDepartcode();
          }else {
              return "error";
          }



    }

    public String  matchRole(Long newRoidId,Long oldRoidId,String roleName)
    {
        if(ObjectUtils.isNotBlank(newRoidId))
        {

            if(newRoidId.equals(oldRoidId))
            {
                return newRoidId.toString();
            }else {
                RolePerEntity role  = rolePerMapper.selectByPrimaryKey(newRoidId);
                if(ObjectUtils.isBlank(role))
                {
                    return newRoidId.toString();
                }else {
                    return "error";
                }


            }
        }else {
            if(StringUtils.isNotBlank(roleName))
            {
                RolePerFilter rolefilter = new RolePerFilter();
                rolefilter.setRole(roleName);
                List<RolePerFilter> list = rolePerMapper.query(rolefilter);
                if(ObjectUtils.isNotBlank(list))
                {
                    return  list.get(0).getId().toString();
                }else {
                    return "error";
                }

            }
        }
        return null;




    }

    @Override
    public UserFilter selectByUserId(Long id) {
        return userEntityMapper.selectUserInfoByUserId(id);
    }
    //插入前先检测 是否已经有用户
    @Override
    public boolean checkUserIsExist(String userName) {

        //插入前先检测 是否已经有用户
        UserFilter userFilter = new UserFilter();
        userFilter.setUserName(userName);
        List<UserFilter> userlists = this.query(userFilter);
        if (userlists.size() > 0) {
            return false;
        }else{
            return true;
        }
    }


    /**
     * 批量修改用户权限
     */
    @Override
    public UserEntity updateRight(Long id, UserFilter filter) {
        /**
         * 拥有可操作的的菜单总量
         */
        UserEntity userEntity = selectUserByPrimaryKey(id);

        String roleRight=null;
        if (ObjectUtils.isNotBlank(filter.getCheckAllGroup())) {
            List<String> rights = filter.getCheckAllGroup();
             roleRight = String.join(",", rights);
        }
        userEntity.setRoleRight(roleRight);
        /*
         * 乡镇指标
         */
        String townIndex=null;
        if (ObjectUtils.isNotBlank(filter.getCheckAllindexGroup())) {
            List<String> townIndexs = filter.getCheckAllindexGroup();
            townIndex = String.join(",", townIndexs);
        }
        userEntity.setIndexRight(townIndex);
        //市指标
        String strIndex  =null;
        if (ObjectUtils.isNotBlank( filter.getCheckCityGroup())) {
            List<String> indexList = filter.getCheckCityGroup();
            strIndex = String.join(",", indexList);
        }
        userEntity.setCityIndex(strIndex);
        /*
         *单位指标
         */
        String departIndex = null;
        if (ObjectUtils.isNotBlank(filter.getCheckUnitGroup())) {
            List<String> indexList = filter.getCheckUnitGroup();
            departIndex = String.join(",", indexList);

        }
        userEntity.setDepartIndex(departIndex);
        /**
         * 按钮权限
         */
        String StrBtnRight=null;
        if (ObjectUtils.isNotBlank(filter.getBtnRights())) {
            List<String> btnRights = filter.getBtnRights();
            StrBtnRight = String.join(",", btnRights);
        }
        userEntity.setBtnRight(StrBtnRight);


        userEntity.setRoleid(null);

        return userEntity;
    }


    @Override
    public UserEntity selectUserByPrimaryKey(Long id) {
        return userEntityMapper.selectByPrimaryKey(id);
    }
}

